import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
import { getUserInfo } from "@/api/user";
import router from "@/router";
import util from "@/utils/util";

// 定义模块 用户
export const useUserStore = defineStore("user", () => {
  const originalUser = {
    avatar: "",
    nickName: "未登录",
    user_name: "未登录",
    uid: "",
    userId: "",

    front_auth: [],
    token: "",
  };

  // 整体参数
  const user = ref({
    ...originalUser,
  });

  const avatar = computed(() => {
    const avatar = user.value.avatar;
    return avatar
      ? util.getHttpImageUrl(avatar)
      : util.getImageUrl("avatar.png");
  });
  const nickName = computed(() => user.value.nickName);
  const userId = computed(() => user.value.userId || "");
  const token = computed(() => {
    return localStorage.getItem("token") || "";
  });

  // 监听userId
  watch(userId, (n) => {
    console.log("watch userId", n);
  });

  // 登录
  async function login(token) {
    if (token) localStorage.setItem("token", token);

    // 获取用户信息
    await getUserInfo();

    // 返回
    router.go(-1);

    // 进入首页
    // toIndex();
  }

  // 修改参数
  function update(NewValue) {
    user.value = NewValue;
  }

  // 退出登录 还原数据
  function logout() {
    user.value = originalUser;
    localStorage.setItem("token", "");

    // 重新加载当前页面 permission.js 若未登录则自动跳转login
    router.go(0);
    // router.push(`/login`);
  }

  return {
    user,
    avatar,
    nickName,
    userId,
    token,

    // function
    login,
    update,
    logout,
  };
});

// 系统配置
export const useConfigStore = defineStore("config", () => {
  const config = ref({});

  // 修改
  function update(NewValue) {
    config.value = NewValue;
  }

  return {
    config,
    update,
  };
});
